import { useState, useEffect } from 'react'
import type { User } from '@/types'

export const useAuth = () => {
  const [user, setUser] = useState<User | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const checkAuth = async () => {
      try {
        const token = localStorage.getItem('token')
        if (token) {
          // 这里可以添加验证token有效性的API调用
          // const userData = await validateToken(token);
          // setUser(userData);
          setUser({ id: '1', name: 'Demo User', role: 'user' }) // 模拟用户数据
        }
      } catch (error) {
        console.error('Auth check failed:', error)
        localStorage.removeItem('token')
      } finally {
        setLoading(false)
      }
    }

    checkAuth()
  }, [])

  const login = async (credentials: { username: string; password: string }) => {
    // 实际项目中这里应该调用登录API
    const mockUser = { id: '1', name: credentials.username, role: 'user' }
    localStorage.setItem('token', 'mock-token')
    setUser(mockUser)
    return mockUser
  }

  const logout = () => {
    localStorage.removeItem('token')
    setUser(null)
  }

  return { user, loading, login, logout }
}
